<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AnnouncementItem from './AnnouncementItem.vue'
import axios from '../plugins/axios' // 引入你定义的 axios 实例

const router = useRouter()

// 添加地区数据
const regions = ref([])
const currentPinnedRegion = ref('全站')
const currentRealTimeRegion = ref('全站')
const pinnedAnnouncements = ref([]) // 置顶公告
const realTimeAnnouncements = ref([]) // 实时公告
const isLoading = ref(false) // 加载状态

// 定义查询条件
const pinnedAnnouncementsRequestData = ref({
  keyword: '', // 关键字
  siteId: 1, // 站点id，初始为 1
  userId: null, // user_id，可以根据需要传递
  startTime: '', // 开始时间
  endTime: '', // 结束时间
  top: 0, // 是否置顶，0置顶，1 不置顶
  page: 1, // 页码
  rows: 5, // 每页条数
  sortWay: 'DESC', // 排序方式
  sortColumn: 'publish_time', // 排序字段，根据 publishTime 排序
  loginUserId: localStorage.getItem('userId'), // 当前登录的用户id，传递用户的id
})

const realTimeAnnouncementsRequestData = ref({
  keyword: '', // 关键字
  siteId: 1, // 站点id，初始为 1（全站）
  userId: null, // user_id，可以根据需要传递
  startTime: '', // 开始时间
  endTime: '', // 结束时间
  top: 1, // 是否置顶，0 置顶，1 不置顶
  page: 1, // 页码
  rows: 5, // 每页条数
  sortWay: 'DESC', // 排序方式
  sortColumn: 'publish_time', // 排序字段，根据 publishTime 排序
  loginUserId: localStorage.getItem('userId'), // 当前登录的用户id，传递用户的id
})

// 获取地区数据
const fetchRegions = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      console.error('未找到 userId，请先登录')
      return
    }
    const response = await axios.get(`/site/findSiteByUserId/${userId}`)
    if (response.data.code) {
      regions.value = response.data.data
    } else {
      console.error('返回的数据格式不正确')
    }
  } catch (error) {
    console.error('获取地区数据失败:', error)
  }
}

// 发起请求的方法（置顶公告）
const fetchPublicData = async () => {
  isLoading.value = true // 开始加载
  try {
    const response = await axios.post('/public/queryByCondition', pinnedAnnouncementsRequestData.value)
    if (response.data && response.data.code === 1) {
      pinnedAnnouncements.value = response.data.data
    } else {
      console.error('查询失败:', response.data.message)
    }
  } catch (error) {
    console.error('请求失败:', error)
  } finally {
    isLoading.value = false // 结束加载
  }
}

// 发起请求的方法（实时公告）
const fetchRealTimeAnnouncementsData = async () => {
  try {
    const response = await axios.post('/public/queryByCondition', realTimeAnnouncementsRequestData.value)
    if (response.data && response.data.code === 1) {
      realTimeAnnouncements.value = response.data.data
    } else {
      console.error('查询失败:', response.data.message)
    }
  } catch (error) {
    console.error('请求失败:', error)
  }
}

// 在组件挂载时获取地区数据和公告数据
onMounted(() => {
  fetchRegions()
  fetchPublicData()
  fetchRealTimeAnnouncementsData()
})

// 处理置顶公告地区切换
const handlePinnedRegionChange = async (region) => {
  currentPinnedRegion.value = region.siteName // 更新当前选中的地区名称
  pinnedAnnouncementsRequestData.value.siteId = region.id || null // 更新 siteId
  await fetchPublicData() // 重新发起请求
}

// 处理实时公告地区切换
const handleRealTimeRegionChange = async (region) => {
  currentRealTimeRegion.value = region.siteName // 更新当前选中的地区名称
  realTimeAnnouncementsRequestData.value.siteId = region.id || null // 更新 siteId
  await fetchRealTimeAnnouncementsData() // 重新发起请求
}

// 查看更多功能
const handleViewMore = (type) => {
  console.log(`查看更多${type}公告`)
}

// 查看详情功能
const handleViewDetail = (announcement) => {
  router.push(`/announcement/${announcement.id}`)
}

const handlePublicList = (value) => {
  if (value === 0) {
    // 处理 value 为 0 的情况
    router.push({
      path: '/announcement/list/0', // 跳转到 id 为 0 的路由
    })
  } else if (value === 1) {
    // 处理 value 为 1 的情况
    router.push({
      path: '/announcement/list/1', // 跳转到 id 为 1 的路由
    })
  } else {
    console.error('无效的值:', value)
  }
}
</script>

<template>
  <div class="home-page">
    <div v-if="isLoading" class="loading">加载中...</div>
    <div v-else>
      <div class="banner">
        <img src="../assets/banner.png" alt="Banner" class="banner-image" />
      </div>

      <main class="main-content">
        <section class="pinned-announcements">
          <div class="section-header">
            <h2>置顶公告</h2>
            <div class="region-filter">
              <!-- 地区按钮 -->
              <button
                v-for="region in regions"
                :key="region.id"
                :class="{ active: currentPinnedRegion === region.siteName }"
                @click="handlePinnedRegionChange(region)"
              >
                {{ region.siteName }}
              </button>
              <button
                @click="handlePublicList(0)"
              >
                更多>>
              </button>
            </div>
          </div>
          <AnnouncementItem
            :announcements="pinnedAnnouncements"
            :showActions="false"
            @viewDetail="handleViewDetail"
            @viewMore="handleViewMore"
          />
        </section>

        <section class="real-time-announcements">
          <div class="section-header">
            <h2>实时公告</h2>
            <div class="region-filter">
              <!-- 地区按钮 -->
              <button
                v-for="region in regions"
                :key="region.id"
                :class="{ active: currentRealTimeRegion === region.siteName }"
                @click="handleRealTimeRegionChange(region)"
              >
                {{ region.siteName }}
              </button>
              <button
                @click="handlePublicList(1)"
              >
                更多>>
              </button>
            </div>
          </div>
          <AnnouncementItem
            :announcements="realTimeAnnouncements"
            @viewDetail="handleViewDetail"
            :showActions="false"
            @viewMore="() => handleViewMore('实时')"
          />
        </section>
      </main>
    </div>
  </div>
</template>

<style scoped>
.home-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.banner {
  width: 100%;
  height: 300px;
  overflow: hidden;
  margin-bottom: 2rem;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.main-content {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.section-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.25rem;
}

.region-filter {
  display: flex;
  gap: 0.5rem;
}

.region-filter button {
  padding: 0.25rem 0.75rem;
  border: none;
  background: none;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.region-filter button.active {
  color: #0052cc;
  font-weight: bold;
}

.region-filter button.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: #0052cc;
}

/* 为"更多"按钮添加特殊样式 */
.region-filter button:last-child {
  color: #409EFF;
  font-weight: bold;
}

.region-filter button:last-child:hover {
  color: #66b1ff;
}

.pinned-announcements,
.real-time-announcements {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading {
  text-align: center;
  padding: 1rem;
  font-size: 1.2rem;
  color: #666;
}
</style>